package com.mimc.controller.api;

import cn.hutool.core.date.DateUtil;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Page;
import com.mimc.core.model.ImApply;
import com.mimc.core.model.ImFriend;
import com.mimc.core.model.ImUser;
import com.mimc.core.service.ImApplyService;
import com.mimc.core.service.ImFriendService;
import com.mimc.core.service.ImUserService;
import com.mimc.framework.domain.AjaxResult;
import com.mimc.framework.utils.ShConfigUtil;
import io.jboot.aop.annotation.Transactional;
import io.jboot.db.model.Columns;
import io.jboot.utils.StrUtil;
import io.jboot.web.controller.annotation.RequestMapping;

import java.util.Date;
import java.util.List;

@RequestMapping("/api/friend")
public class FriendController extends BaseController {
    @Inject
    private ImApplyService imApplyService;
    @Inject
    private ImFriendService imFriendService;
    @Inject
    private ImUserService imUserService;
    /**
     * 申请好友
     * @return
     */
    public AjaxResult apply(){
        Long toId=getParaToLong("toId");//目标用户
        String reason=getPara("reason");//申请理由
        if(toId==null){
            return AjaxResult.error(translate("确实目标用户参数"));
        }
        if(StrUtil.isBlank(reason)){
            return AjaxResult.error(translate("请输入申请理由"));
        }
        //判断是否是好友
        ImFriend friend=imFriendService.findFirstByColumns(Columns.create("to_id",toId).eq("from_id",getUserId()));
        if(friend!=null){
            return AjaxResult.error(translate("已是好友无需再申请"));
        }
        //查询最近10天是否有请求
        Columns columns=Columns.create();
        Date now= new Date();
        columns.between("created_time",DateUtil.offsetDay(now,-10),now);
        ImApply hasApply=imApplyService.findFirstByColumns(columns);
        if(hasApply!=null){
            return AjaxResult.error(translate("最近申请过该好友"));
        }
        ImApply apply=new ImApply();
        apply.setToId(toId);
        apply.setReason(reason);
        apply.setFromId(getUserId());
        apply.setApplySource(getSource());
        apply.setApplyType(1);
        apply.setApplyStatus(0);
        apply.setCreatedTime(new Date());
        apply.setUpdatedTime(new Date());
        imApplyService.save(apply);
        return AjaxResult.success(translate("申请已提交"));
    }
    //申请加我的列表，只显示10天内的
    public AjaxResult requestList(){
        int page=getInt("page",1);
        int pageSize=getInt("pageSize",15);
        //查询最近10天是否有请求
        Columns columns=Columns.create();
        Date now= new Date();
        columns.between("create_time",DateUtil.offsetDay(now,-10),now);
        columns.eq("to_id",getUserId());
        Page<ImApply> applyList=imApplyService.paginateByColumns(page,pageSize,columns,"create_time desc");
        return AjaxResult.success(translate("获取成功"),applyList);
    }

    /**
     * 确认加好友
     * @return
     */
    public AjaxResult sure(){
        Long id=getParaToLong("id");
        ImApply apply=imApplyService.findFirstByColumns(Columns.create("id",id).eq("to_id",getUserId()));
        if(apply==null){
            return AjaxResult.error(translate("对不起，不存在该申请"));
        }
        //判断好友是否上限
        Long count=imFriendService.findCountByColumns(Columns.create("from_id",getUserId()));
        if(count>= ShConfigUtil.imFriendLimit()){
            return AjaxResult.error(translate("对不起，你的好友人数已上限"));
        }
        //判断是否是好友
        ImFriend friend=imFriendService.findFirstByColumns(Columns.create("to_id",apply.getFromId()).eq("from_id",getUserId()));
        if(friend!=null){
            return AjaxResult.error(translate("已是好友无需再申请"));
        }
        apply.setUpdatedTime(new Date());
        apply.setApplyStatus(1);
        if(imApplyService.update(apply)){
            //双向添加好友
            //对方
            ImUser newUser=imUserService.findById(apply.getFromId());
            int newVersion=newUser.getFriendVersion()+1;
            newUser.setFriendVersion(newVersion);
            imUserService.update(newUser);
            ImFriend newFriend=new ImFriend();
            newFriend.setFromId(apply.getFromId());
            newFriend.setToId(apply.getToId());
            newFriend.setSource(apply.getApplySource());
            newFriend.setCreatedTime(new Date());
            newFriend.setUpdatedTime(new Date());
            newFriend.setVersion(newVersion);
            imFriendService.save(newFriend);
            //更新版本
            //自己
            ImUser myUser=imUserService.findById(apply.getToId());
            int myVersion=newUser.getFriendVersion()+1;
            myUser.setFriendVersion(myVersion);
            imUserService.update(myUser);
            ImFriend myFriend=new ImFriend();
            myFriend.setFromId(apply.getToId());
            myFriend.setToId(apply.getFromId());
            myFriend.setSource(apply.getApplySource());
            myFriend.setCreatedTime(new Date());
            myFriend.setUpdatedTime(new Date());
            myFriend.setVersion(myVersion);
            imFriendService.save(myFriend);
        }
        return AjaxResult.success(translate("已确认添加好友"));
    }

    /**
     * 拒绝添加好友申请
     * @return
     */
    public AjaxResult refuse(){
        Long id=getParaToLong("id");
        ImApply apply=imApplyService.findFirstByColumns(Columns.create("id",id).eq("to_id",getUserId()));
        if(apply==null){
            return AjaxResult.error(translate("对不起，不存在该申请"));
        }
        apply.setApplyStatus(2);
        apply.setUpdatedTime(new Date());
        imApplyService.update(apply);
        return AjaxResult.success(translate("已拒绝"));
    }

    /**
     * 忽略好友申请
     * @return
     */
    public AjaxResult ignore(){
        Long id=getParaToLong("id");
        ImApply apply=imApplyService.findFirstByColumns(Columns.create("id",id).eq("to_id",getUserId()));
        if(apply==null){
            return AjaxResult.error(translate("对不起，不存在该申请"));
        }
        apply.setApplyStatus(3);
        apply.setUpdatedTime(new Date());
        imApplyService.update(apply);
        return AjaxResult.success(translate("已忽略"));
    }
    /**
     * 搜索好友
     * @return
     */
    public AjaxResult search(){
        String keyword=getPara("keyword");
        ImUser user=imUserService.findFirstByColumns(Columns.create("email",keyword).or().eq("chat_no",keyword));
        if(user==null){
            return AjaxResult.error(translate("不存在该好友"));
        }
        if(user.getUserId().intValue()==getUserId().intValue()){
            return AjaxResult.error(translate("自己"));
        }
        ImFriend friend=imFriendService.findFirstByColumns(Columns.create("to_id",user.getUserId()).eq("from_id",getUserId()));
        Boolean isFriend=friend!=null;
        return AjaxResult.success(translate("成功"),user).put("isFriend",isFriend);
    }
    public AjaxResult isFriend(){
        Long toId=getParaToLong("toId");
        ImFriend friend=imFriendService.findFirstByColumns(Columns.create("to_id",toId).eq("from_id",getUserId()));
        Boolean isFriend=friend!=null;
        return AjaxResult.success(translate("成功"),isFriend);
    }
    /**
     *更新备注
     * @return
     */
    public AjaxResult updateRemark(){
        Long friendId=getLong("friendId");
        String remark=getPara("remark");
        if(StrUtil.isBlank(remark)){
            return AjaxResult.error(translate("请输入备注"));
        }
        ImFriend friend=imFriendService.findById(friendId);
        if(friend==null){
            return AjaxResult.error(translate("好友不存在"));
        }
        friend.setRemark(remark);
        friend.setVersion(incUserFriendVersion());
        friend.setUpdatedTime(new Date());
        imFriendService.update(friend);
        return AjaxResult.success(translate("更新成功"),friend);
    }

    /**
     * 删除好友
     * @return
     */
    @Transactional
    public AjaxResult delete(){
        Long friendId=getLong("friendId");
        ImFriend friend=imFriendService.findById(friendId);
        if(friend==null){
            return AjaxResult.error(translate("好友不存在"));
        }
        if(friend.getFromId()!=getUserId()){
            return AjaxResult.error(translate("对不起，无权删除"));
        }
        //对方数据
        ImFriend youFriend=imFriendService.findFirstByColumns(Columns.create("to_id",friend.getFromId()).eq("from_id",friend.getToId()));
        if(youFriend!=null){
            youFriend.delete();
        }
        friend.delete();
        return AjaxResult.success(translate("删除成功"));
    }

    /**
     * 同步好友
     * @return
     */
    public AjaxResult sync(){
        //Integer limit=getInt("limit",100);
        Integer version=getInt("version",0);
        Columns columns=Columns.create("from_id",getUserId());
        columns.gt("version",version);
        List<ImFriend> friendList=imFriendService.findListByColumns(columns,"update_date desc");
        return AjaxResult.success(translate("获取成功"),friendList);
    }

}
